import API from "@/api";

interface FreetalkEvaluating {
  audioBuffer: ArrayBuffer;
  onSuccess: (result: AnyObject) => void;
  onError: (errorMsg: string) => void;
}

async function baseGetAuth(callback: Function) {
  let token = '';
  try {
    const res: any = await API.getwrAuth({});
    token = res.auth_key;
  } catch (e) {
    console.error(e);
  } finally {
    callback && callback(token);
  }
}

export function startEvaluating(data: FreetalkEvaluating) {
  // 设置请求头

  baseGetAuth((auth_key: any) => {
    let headers: any = {
      "Content-type": "audio/wav",
      "Pronunciation-Assessment":
          "eyJHcmFkaW5nU3lzdGVtIjoiSHVuZHJlZE1hcmsiLCJHcmFudWxhcml0eSI6IlBob25lbWUiLCJEaW1lbnNpb24iOiJDb21wcmVoZW5zaXZlIiwiUGhvbmVtZUFscGhhYmV0IjoiSVBBIiwiRW5hYmxlUHJvc29keUFzc2Vzc21lbnQiOnRydWUsIkVuYWJsZU1pc2N1ZSI6dHJ1ZX0=",
      Accept: "application/json",
    }

    auth_key ? (headers['Authorization'] = auth_key) : (headers['Ocp-Apim-Subscription-Key'] = "8ce74b4639fd4d4d832bb854058cb2dc");

    uni.request({
      url: "https://eastasia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed",
      data: data.audioBuffer,
      header: headers,
      method: "POST",
      success: (res) => {
        console.log(res.data);
        data.onSuccess(res.data as AnyObject);
      },
      fail: (error) => {
        console.error(error.errMsg);
        data.onError(error.errMsg);
      },
    });
  })
}


type SuccessParams = { filePath: string }
interface IVoiceCreateInfo {
  content: string;
  onSuccess: (data: SuccessParams) => void;
  onError: (errorMsg: string) => void;
}

export function startCreateVoice(data: IVoiceCreateInfo) {

  baseGetAuth((auth_key: any) => {
    let headers: any = {
      "Content-type": "application/ssml+xml",
      "X-Microsoft-OutputFormat": "audio-16khz-128kbitrate-mono-mp3",
    }

    auth_key ? (headers['Authorization'] = auth_key) : (headers['Ocp-Apim-Subscription-Key'] = "8ce74b4639fd4d4d832bb854058cb2dc");

    uni.request({
      url: "https://eastasia.tts.speech.microsoft.com/cognitiveservices/v1",
      data: `<speak version='1.0' xml:lang='en-US'><voice name='en-US-JennyNeural'>${data.content}</voice></speak>`,
      header: headers,
      method: "POST",
      responseType: "arraybuffer",
      success: (res) => {
        let path = `${wx.env.USER_DATA_PATH}/${(new Date()).valueOf()}.mp3`;

        uni.getFileSystemManager().writeFile({
          filePath: path,
          data: res.data as string,
          encoding: 'binary',
          success(res) {
            data.onSuccess({
              filePath: path
            });
          },
          fail(err) {
            console.error('音频文件保存失败:', err.errMsg);
            data.onError(err.errMsg);
          }
        });
      },
      fail: (error) => {
        debugger
        console.error(error.errMsg);
        data.onError(error.errMsg);
      },
    });
  })
}